/**
 * 
 */
package org.braketester.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.braketester.entry.ExceptionResolver;

/**
 * @author LAP
 *
 */
public class PreferencesLoader {
	
	private PreferencesLoader() {
		
	}
	
	private static class PreferencesLoaderHolder {
		public static final PreferencesLoader INSTANCE = new PreferencesLoader();
	}
	
	public static PreferencesLoader getInstance() {
		return PreferencesLoaderHolder.INSTANCE;
	}
	
	public void savePreferences(Object preferences) {
		tryWriteObjectOutputStream(preferences);
	}
	
	private FileOutputStream tryCreateFileOutputStream(Object preferences) {
		FileOutputStream fos = null;
		try {
			File pref = new File(".\\pref\\" + preferences.getClass().getSimpleName());
			if (!pref.exists()) pref.createNewFile();
			fos = new FileOutputStream(pref);
		} catch (IOException e) {
			ExceptionResolver.getInstance().logException(e);
			ExceptionResolver.getInstance().showException(e);
		}
		return fos;
	}
	
	private void tryWriteObjectOutputStream(Object preferences) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(tryCreateFileOutputStream(preferences));
			oos.writeObject(preferences);
			oos.flush();
			oos.close();
		} catch (IOException e) {
			ExceptionResolver.getInstance().logException(e);
			ExceptionResolver.getInstance().showException(e);
		}
	}
	
	public Object loadPreferences(Class<?> perferencesClass) throws IOException {
		return tryReadObjectInputStream(perferencesClass);
	}
	
	private Object tryReadObjectInputStream(Class<?> preferencesClass) throws IOException {
		Object ret = null;
		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(".\\pref\\" + preferencesClass.getSimpleName()));
			ret = ois.readObject();
			ois.close();
		} catch (ClassNotFoundException e) {
			ExceptionResolver.getInstance().logException(e);
			ExceptionResolver.getInstance().showException(e);
		}
		return ret;
	}
}
